
<template>
	<div>
		<div class="div">
			<el-button
				class="btn"
				type="primary"
				size="small"
			><i class="el-icon-share"></i> {{btnText}}</el-button>
			<input
				class="input"
				type="file"
				ref="upload"
				accept=".xls, .xlsx"
				@change="readExcel($event)"
			/>
		</div>
		<el-table
			:data="tableData"
			style="width: 100%"
			height="17rem"
		>
			<template v-for='(col,index) in tableHead'>
				<el-table-column
					:prop="col"
					:label="col"
					:key="index"
					align="center"
				></el-table-column>
			</template>
		</el-table>
	</div>
</template>
<script>
	import XLSX from 'xlsx'
	export default {
		name: 'Test',
		data() {
			return {
				tableData: [],
				tableHead: [],
				btnText: '导入',
				fileList: []
			}
		},
		methods: {
			readExcel(e) {
				//表格导入
				var that = this
				const files = e.target.files
				if (files.length <= 0) {
					//如果没有文件名
					return false
				} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
					this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
					return false
				}

				const fileReader = new FileReader()
				fileReader.onload = (ev) => {
					try {
						const data = ev.target.result
						const workbook = XLSX.read(data, {
							type: 'binary'
						})
						const wsname = workbook.SheetNames[0] //取第一张表
						const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
						that.tableData = [] //清空接收数据
						that.tableHead = []
						for (let item in ws[0]) {
							that.tableHead.push(item)
						}
						that.tableData = ws
						this.$refs.upload.value = ''
					} catch (e) {
						return false
					}
				}
				fileReader.readAsBinaryString(files[0])
			}
		}
	}
</script>
<style lang="css" scoped>
	.div {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-bottom: 3rem;
		position: relative;
	}
	.btn {
		position: absolute;
		top: 1rem;
		right: 0;
		z-index: 1;
	}
	.input {
		position: absolute;
		top: 1rem;
		right: 0;
		z-index: 999;
		opacity: 0;
		height: 1.5rem;
		cursor: pointer;
		width: 3.5rem;
	}
	/*滚动条的宽度*/
	/deep/ .el-table__body-wrapper::-webkit-scrollbar {
		width: 6px;
		height: 6px;
	}
	/*滚动条滑块*/
	/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
		background-color: #ddd;
		border-radius: 3px;
	}
</style>

